%concatinates arrays of unequal size by filling in the with NaNs


function r = nancat_v2(a,b,dim)

if isempty(a)
    m1 = 0;n1 = 0;p1 = 0;q1 = 0;
else
    [m1,n1,p1,q1] = size(a);
end
if isempty(b)
    m2 = 0;n2 = 0;p2 = 0;q2 = 0;
else
    [m2,n2,p2,q2] = size(b);
end



maxdims = max(ndims(a),ndims(b));
switch dim
    case 1
        r = nan(m1+m2,max(n1,n2),max(p1,p2),max(q1,q2));
    case 2
        r = nan(max(m1,m2),n1+n2,max(p1,p2),max(q1,q2));
    case 3
        r = nan(max(m1,m2),max(n1,n2),p1+p2,max(q1,q2));
    case 4
        r = nan(max(m1,m2),max(n1,n2),max(p1,p2),q1+q2);
end
ndims_final = ndims(r);
switch dim
    case 1
        r(1:m1,1:n1,1:p1,1:q1) = a;
        r((m1+1):(m1+n2),1:n2,1:p2,1:q2) = b;
    case 2
        r(1:m1,1:n1,1:p1,1:q1) = a;
        r(1:m2,(n1+1):(n1+n2),1:p2,1:q2) = b;
    case 3
        r(1:m1,1:n1,1:p1,1:q1) = a;
        r(1:m2,1:n2,(p1+1):(p1+p2),1:q2) = b;
    case 4
        r(1:m1,1:n1,1:p1,1:q1) = a;
        r(1:m2,1:n2,1:p2,(q1+1):(q1+q2)) = b;
end



